<?php
//Checkout -> 05 Payment
//checkout05payment.php

//TMP DEFINES
define("SHOPNAME", "Schanaz");
define("SHOPEMAIL", "shop@sptnkswthrt.com");
define("SHOPEMAILTITLE", "Billing Status");
define("VERIFYKEY", "a873af1f52f8a91750e1f137e5bd8dce");
define("MERCHANTID", "sptnkswthrt");
define("PERIOD", (36*60*60));
define("CURRENCY", "myr");
define("BILLID", "schanaz");

  $insert_deal = TRUE;
  $revert_deal = TRUE;
  $insert_bill = TRUE;

  if(!isset($_SESSION['shoppingBag'])) {
    $_SESSION['shoppingBag'] = array();
  }

  sort($_SESSION['shoppingBag']);
  $bagUnique = array_unique($_SESSION['shoppingBag']);
  $bagCount = array_count_values($_SESSION['shoppingBag']);

  $bagProd = array();
  $bagProd = bag_construction($db);

  sort($_SESSION['shoppingBag']);
  $bagUnique = array_unique($_SESSION['shoppingBag']);
  $bagCount = array_count_values($_SESSION['shoppingBag']);

  $queries = array();

  //INSERT Address
  $params = array();
  $params[] = array(1, 2, 3, 4, 5, 6, 7, 8);
  $params[] = array(  $_SESSION['checkOut']['address-fullname']
                    , $_SESSION['checkOut']['address-street1']
                    , $_SESSION['checkOut']['address-street2']
                    , $_SESSION['checkOut']['address-city']
                    , $_SESSION['checkOut']['address-state']
                    , $_SESSION['checkOut']['address-postcode']
                    , $_SESSION['checkOut']['address-country']
                    , $_SESSION['checkOut']['address-phone']
                    );
  $query = $db->db_insert("address", $params);
  $queries[] .= $query.";";
  if ($insert_deal) {
    $result = $db->database->query($query);
    $_SESSION['checkOut']['address-id'] = $db->database->lastInsertRowid();
  }

  //INSERT Customer
  $params = array();
  $params[] = array(1, 2, 3);
  $params[] = array(  $_SESSION['checkOut']['email-address']
                    , $_SESSION['checkOut']['logintype']
                    , $_SESSION['checkOut']['address-id']
                    );
  $query = $db->db_insert("customer", $params);
  $queries[] .= $query.";";
  if ($insert_deal) {
    $result = $db->database->query($query);
    $_SESSION['checkOut']['customer-id'] = $db->database->lastInsertRowid();
  }

  //INSERT Deal
  $deal_timestamp = time();
  $params = array();
  $params[] = array(1, 3, 4);
  $params[] = array(  $deal_timestamp
                    , $_SESSION['checkOut']['customer-id']
                    , $_SESSION['checkOut']['address-id']
                    );
  $query = $db->db_insert("deal", $params);
  $queries[] .= $query.";";
  if ($insert_deal) {
    $result = $db->database->query($query);
    $_SESSION['checkOut']['deal-id'] = $db->database->lastInsertRowid();
  }

  //INSERT Product2Deal
  foreach($bagProd as $value) {
    for($i = 0; $i < $bagCount[$value['product_id']]; $i++) {
      $params = array();
      $params[] = array(1, 2, 3);
      $params[] = array(  $value['product_id']
                        , $_SESSION['checkOut']['deal-id']
                        , $value['product_price']
                        );
      $query = $db->db_insert("product2deal", $params);
      $queries[] .= $query.";";
      if ($insert_deal) {
        $result = $db->database->query($query);
        $_SESSION['checkOut']['product2deal-ids'][] = $db->database->lastInsertRowid();
      }
    }
    //UPDATE Product
    $params = array();
    $params[] = array(3);
    $params[] = array(($value['product_quantity'] - $bagCount[$value['product_id']]));
    $conds = array();
    $conds[] = array(0);
    $conds[] = array(0);
    $conds[] = array($value['product_id']);
    $query = $db->db_update("product", $params, $conds);
    $queries[] .= $query.";";
    if ($insert_deal) {
      $result = $db->database->query($query);
      $_SESSION['checkOut']['product-ids'][] = $value['product_id'];
    }
  }

  if ($insert_deal) {
    //Check for -(ve) product quantity
    $prodIds = "";
    $prodIds = implode(",", $bagUnique);
    $cols = array(0);
    $conds = array();
    $conds[] = array(3);// product_quantity
    $conds[] = array(3);// <
    $conds[] = array(0);// '0'
    $query = $db->db_select("product", $cols, $conds)." AND product_id IN (".$prodIds.")";
    $result = $db->database->query($query);
    $errProd = $result->fetchAll(SQLITE_ASSOC);
  }

  if (!empty($errProd)) {
    //product_quantity ERROR!!!

    //Get Deal
    $cols = NULL;
    $conds = array();
    $conds[] = array(0);
    $conds[] = array(0);
    $conds[] = array($_SESSION['checkOut']['deal-id']);
    $query = $db->db_select("deal", $cols, $conds);
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpDeal = $result->fetchAll(SQLITE_ASSOC);
/*
    //Get Customer
    $cols = NULL;
    $conds = array();
    $conds[] = array(0);
    $conds[] = array(0);
    $conds[] = array($tmpDeal[0]['customer_id']);
    $query = $db->db_select("customer", $cols, $conds);
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpCust = $result->fetchAll(SQLITE_ASSOC);

    //Get Address
    $cols = NULL;
    $conds = array();
    $conds[] = array(0);
    $conds[] = array(0);
    $conds[] = array($tmpDeal[0]['address_id']);
    $query = $db->db_select("address", $cols, $conds);
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpAddr = $result->fetchAll(SQLITE_ASSOC);
*/
    //Get Product2Deal
    $cols = NULL;
    $conds = array();
    $conds[] = array(2);
    $conds[] = array(0);
    $conds[] = array($tmpDeal[0]['deal_id']);
    $query = $db->db_select("product2deal", $cols, $conds);
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpProd2Deal = $result->fetchAll(SQLITE_ASSOC);

    //Construct Temp BAG
    $prodIds = array();
    foreach ($tmpProd2Deal as $value) {
      $prodIds[] = $value["product_id"];
    }
    sort($prodIds);
    $prodIdsUnique = array_unique($prodIds);
    $prodIdsCount = array_count_values($prodIds);

    //Construct Temp PRODUCT
    $prodIdsUniqueStr = implode(",", $prodIdsUnique);
    $query = "SELECT * FROM product WHERE product_id in (".$prodIdsUniqueStr.")";
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpProd = $result->fetchAll(SQLITE_ASSOC);

    //REVERT product_quantity
    foreach($tmpProd as $value) {
      $params = array();
      $params[] = array(3);
      $params[] = array(($value['product_quantity'] + $prodIdsCount[$value['product_id']]));
      $conds = array();
      $conds[] = array(0);
      $conds[] = array(0);
      $conds[] = array($value['product_id']);
      $query = $db->db_update("product", $params, $conds);
      $queries[] .= $query.";";
      if($revert_deal) {
        $result = $db->database->query($query);
      }
    }

    //REVERT product2deal
    $conds = array();
    $conds[] = array(2);
    $conds[] = array(0);
    $conds[] = array($tmpDeal[0]['deal_id']);
    $query = $db->db_delete("product2deal", $conds);
    $queries[] .= $query.";";
    if($revert_deal) {
      $result = $db->database->query($query);
    }

    //REVERT deal
    $conds = array();
    $conds[] = array(0);
    $conds[] = array(0);
    $conds[] = array($tmpDeal[0]['deal_id']);
    $query = $db->db_delete("deal", $conds);
    $queries[] .= $query.";";
    if($revert_deal) {
      $result = $db->database->query($query);
    }

    //REVERT customer (if GUEST)
    if ($tmpCust[0][customer_loginby] == "GUEST") {
      $conds = array();
      $conds[] = array(0);
      $conds[] = array(0);
      //$conds[] = array($tmpCust[0]['customer_id']);
      $conds[] = array($tmpDeal[0]['customer_id']);
      $query = $db->db_delete("customer", $conds);
      $queries[] .= $query.";";
      if($revert_deal) {
        $result = $db->database->query($query);
      }
    }

    //REVERT address (if GUEST)
    if ($tmpCust[0][customer_loginby] == "GUEST") {
      $conds = array();
      $conds[] = array(0);
      $conds[] = array(0);
      //$conds[] = array($tmpAddr[0]['address_id']);
      $conds[] = array($tmpDeal[0]['address_id']);
      $query = $db->db_delete("address", $conds);
      $queries[] .= $query.";";
      if($revert_deal) {
        $result = $db->database->query($query);
      }
    }

    //Redirect!!!
    pageRedirect($_SERVER['PHP_SELF']."?error&do=order");
  } else {

    //Get Deal
    $cols = NULL;
    $conds = array();
    $conds[] = array(0);
    $conds[] = array(0);
    $conds[] = array($_SESSION['checkOut']['deal-id']);
    $query = $db->db_select("deal", $cols, $conds);
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpDeal = $result->fetchAll(SQLITE_ASSOC);

    //Get Customer
    $cols = NULL;
    $conds = array();
    $conds[] = array(0);
    $conds[] = array(0);
    $conds[] = array($tmpDeal[0]['customer_id']);
    $query = $db->db_select("customer", $cols, $conds);
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpCust = $result->fetchAll(SQLITE_ASSOC);

    //Get Address
    $cols = NULL;
    $conds = array();
    $conds[] = array(0);
    $conds[] = array(0);
    $conds[] = array($tmpDeal[0]['address_id']);
    $query = $db->db_select("address", $cols, $conds);
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpAddr = $result->fetchAll(SQLITE_ASSOC);

    //Get Postage
    $cols = NULL;
    $conds = array();
    $conds[] = array(1);
    $conds[] = array(0);
    $conds[] = array($tmpAddr[0]['address_country']);
    $query = $db->db_select("postage", $cols, $conds);
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpPostg = $result->fetchAll(SQLITE_ASSOC);

    //Get Product2Deal
    $cols = NULL;
    $conds = array();
    $conds[] = array(2);
    $conds[] = array(0);
    $conds[] = array($tmpDeal[0]['deal_id']);
    $query = $db->db_select("product2deal", $cols, $conds);
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpProd2Deal = $result->fetchAll(SQLITE_ASSOC);

    //Construct Temp BAG
    $prodIds = array();
    foreach ($tmpProd2Deal as $value) {
      $prodIds[] = $value["product_id"];
    }
    sort($prodIds);
    $prodIdsUnique = array_unique($prodIds);
    $prodIdsCount = array_count_values($prodIds);

    //Construct Temp PRODUCT
    $prodIdsUniqueStr = implode(",", $prodIdsUnique);
    $query = "SELECT * FROM product WHERE product_id in (".$prodIdsUniqueStr.")";
    $queries[] .= $query.";";
    $result = $db->database->query($query);
    $tmpProd = $result->fetchAll(SQLITE_ASSOC);

    //INSERT Bill
    $bill_postage = sprintf("%01.2f", $tmpPostg[0]['postage_country_price']);
    $bill_price[] = 0;
    foreach($tmpProd2Deal as $value) {
      $bill_price[] = $value["product_price"];
    }
    $bill_totprice = sprintf("%01.2f", (array_sum($bill_price) + $bill_postage));
    $bill_orderid = sprintf("%s%010s", BILLID, $tmpDeal[0]["deal_id"]);
    $bill_desc = "";
    foreach ($tmpProd as $key => $value) {
      if ($key == 0) {
        $bill_desc .= $value["product_name"];
      } else {
        $bill_desc .= ", ";
        $bill_desc .= $value["product_name"];
      }
    }
    $bill_vcode = md5($bill_totprice.MERCHANTID.$bill_orderid.VERIFYKEY);
    $bill_returnurl = "http://stick.sptnkswthrt.com/partial/admin/payment.php";
    $bill_url = "";
    $bill_url .= "https://www.onlinepayment.com.my/NBepay/pay/".MERCHANTID."/?";
    $bill_url .= "amount=".$bill_totprice."&";
    $bill_url .= "orderid=".$bill_orderid."&";
    $bill_url .= "bill_name=".urlencode($tmpAddr[0]["address_fullname"])."&";
    $bill_url .= "bill_email=".urlencode($tmpCust[0]["customer_email"])."&";
    $bill_url .= "bill_mobile=".urlencode($tmpAddr[0]["address_phone"])."&";
    $bill_url .= "bill_desc=".urlencode($bill_desc)."&";
    $bill_url .= "cur=".urlencode(CURRENCY)."&";
    $bill_url .= "returnurl=".$bill_returnurl."&";
    $bill_url .= "vcode=".$bill_vcode."&";
    $bill_url .= "country=".$tmpPostg[0]['postage_country_code'];

    $params = array();
    $params[] = array(1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
    $params[] = array(  time()
                      , PERIOD
                      , $bill_postage
                      , $bill_totprice
                      , $bill_orderid
                      , $tmpAddr[0]["address_fullname"]
                      , $tmpCust[0]["customer_email"]
                      , $tmpAddr[0]["address_phone"]
                      , CURRENCY
                      , $bill_desc
                      , $bill_vcode
                      , $bill_returnurl
                      , $bill_url
                      , $tmpDeal[0]["deal_id"]
                      );
    $query = $db->db_insert("bill", $params);
    $queries[] .= $query.";";
    if ($insert_bill) {
      $result = $db->database->query($query);
      $bill_id = $db->database->lastInsertRowid();
    }

    $params = array();
    $params[] = array(2);
    $params[] = array("billed");
    $conds = array();
    $conds[] = array(0);
    $conds[] = array(0);
    $conds[] = array($tmpDeal[0]["deal_id"]);
    $query = $db->db_update("deal", $params, $conds);
    $queries[] .= $query.";";
    if($insert_bill) {
      $result = $db->database->query($query);
    }

    if ($insert_bill) {
      unset($_SESSION['shoppingBag']);
      unset($_SESSION['checkOut']);
    }
/*
    echo "<br />";
    echo "<pre>";
    print_r($queries);
    print_r($tmpDeal);
    print_r($tmpCust);
    print_r($tmpAddr);
    print_r($tmpPostg);
    print_r($tmpProd2Deal);
    echo "</pre>";
    printPayOnline($bill_url);
*/
    
    //Send e-mail!!!
    
    //recipients
    $tmpEmailTo = $tmpAddr[0]["address_fullname"]." <".$tmpCust[0]["customer_email"].">"."\r\n";
    //subject
    $tmpEmailSubject = SHOPNAME." ".SHOPEMAILTITLE."\r\n";
    //message
    $tmpEmailMessage  = file_get_contents("http://stick.sptnkswthrt.com/partial/admin/genemail.php?dealid=".$tmpDeal[0]["deal_id"]."&email=".$tmpCust[0]["customer_email"]."");
    $tmpEmailMessage .= "\r\n";
    //to send HTML mail, the Content-type header must be set
    $tmpEmailHeaders  = "MIME-Version: 1.0"."\r\n";
    $tmpEmailHeaders .= "Content-type: text/html; charset=iso-8859-1"."\r\n";
    //additional headers
    //$tmpEmailHeaders .= "To: ".$tmpAddr[0]["address_fullname"]." <".$tmpCust[0]["customer_email"].">"."\r\n";
    $tmpEmailHeaders .= "From: ".SHOPNAME." <".SHOPEMAIL.">"."\r\n";
    $tmpEmailHeaders .= "Reply-To: ".SHOPNAME." <".SHOPEMAIL.">"."\r\n";
    $tmpEmailHeaders .= "X-Mailer: PHP/".phpversion();
    //mail it
    $result = mail($tmpEmailTo, $tmpEmailSubject, $tmpEmailMessage, $tmpEmailHeaders);
    
    //Redirect!!!
    pageRedirect("http://stick.sptnkswthrt.com/partial/admin/transaction.php?dealid=".$tmpDeal[0]["deal_id"]."&email=".$tmpCust[0]["customer_email"]);
  }
?>
<?php
?>